//The MIT License

//Copyright (c) 2009 Lluis Sanchez, Nick Darnell

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Polymorph.Properties;

namespace Polymorph
{
    public class CodeMethodCall : CodeExpression
    {
        private CodeExpression m_target;
        private CodeExpression[] m_parameters;
        private MethodInfo m_method;
        private CodeMethod m_codeMethod;

        public CodeMethodCall(CodeExpression target, string name, 
            params CodeExpression[] parameters)
        {
            m_target = target;
            m_parameters = parameters;

            Type[] types = GetParameterTypes(parameters);
            m_method = TypeEx.GetAnyMethod(target.ResultType, name,
                BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance, types);

            if (m_method == null)
            {
                throw new InvalidOperationException(
                    string.Format(GetSignature(target.ResultType, name, parameters),
                    Resources.Method0NotFound));
            }
        }

        public CodeMethodCall(CodeExpression target, MethodInfo method,
            params CodeExpression[] parameters)
        {
            m_target = target;
            m_parameters = parameters;
            m_method = method;
        }

        public CodeMethodCall(CodeExpression target, CodeMethod method,
            params CodeExpression[] parameters)
        {
            m_target = target;
            m_parameters = parameters;
            m_codeMethod = method;
        }

        public CodeMethodCall(Type type, string name, params CodeExpression[] parameters)
        {
            m_parameters = parameters;

            m_method = type.GetMethod(name,
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
                null, GetParameterTypes(parameters), null);

            if (m_method == null)
            {
                throw new InvalidOperationException(
                    string.Format(GetSignature(type, name, parameters),
                    Resources.Method0NotFound));
            }
        }

        public CodeMethodCall(MethodInfo method, params CodeExpression[] parameters)
        {
            if (method == null)
                throw new ArgumentNullException("method");

            m_parameters = parameters;
            m_method = method;
        }

        public CodeMethodCall(CodeMethod method, params CodeExpression[] parameters)
        {
            if (method == null)
                throw new ArgumentNullException("method");

            m_parameters = parameters;
            m_codeMethod = method;
        }

        Type[] GetParameterTypes(CodeExpression[] parameters)
        {
            Type[] ts = new Type[parameters.Length];
            
            for (int n = 0; n < ts.Length; n++)
                ts[n] = parameters[n].ResultType;

            return ts;
        }

        string GetSignature(Type type, string name, params CodeExpression[] parameters)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(type.FullName).Append(".").Append(name);

            Type[] types = GetParameterTypes(parameters);
            sb.Append("(");
            for (int n = 0; n < types.Length; n++)
            {
                if (n > 0) sb.Append(", ");
                sb.Append(types[n].FullName);
            }
            sb.Append(")");
            return sb.ToString();
        }

        public override void Generate(ILGenerator gen)
        {
            if (m_codeMethod != null)
                CodeGenerationHelper.GenerateMethodCall(gen, m_target, m_codeMethod, m_parameters);
            else
                CodeGenerationHelper.GenerateMethodCall(gen, m_target, m_method, m_parameters);
        }

        public override void GenerateAsStatement(ILGenerator gen)
        {
            Generate(gen);

            if (ResultType != typeof(void))
                gen.Emit(OpCodes.Pop);
        }

        public override void PrintCode(CodeWriter cp)
        {
            MethodBase met = m_method != null ? m_method : m_codeMethod.MethodInfo;
            if (!object.ReferenceEquals(m_target, null))
                m_target.PrintCode(cp);
            else
                cp.Write(met.DeclaringType.FullName);

            cp.Write(".");
            cp.Write(met.Name).Write("(");
            for (int n = 0; n < m_parameters.Length; n++)
            {
                if (n > 0) cp.Write(", ");
                m_parameters[n].PrintCode(cp);
            }
            cp.Write(")");
        }

        public override Type ResultType
        {
            get
            {
                if (m_codeMethod != null)
                    return m_codeMethod.ReturnType;
                else
                    return m_method.ReturnType;
            }
        }
    }
}